package services.common;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.common.bean.CreditorRight;
import models.common.bean.CreditorRightDebt;
import models.common.bean.CurrUser;
import models.common.bean.MonthlySummary;
import models.common.bean.PecuniaCredita;
import models.common.bean.QuotaApplicationBean;
import models.common.bean.ReceptionTicketRight;
import models.common.bean.TicketAwayBean;
import models.common.bean.TicketRights;
import models.common.entity.t_bank_list;
import models.common.entity.t_company_info;
import models.common.entity.t_company_info_side;
import models.common.entity.t_creditor_right_debt;
import models.common.entity.t_event_user;
import models.common.entity.t_creditor_right_debt.CreditorRightDebtStatus;

import org.apache.commons.lang.StringUtils;

import play.mvc.Http.Request;

import services.base.BaseService;

import com.shove.Convert;
import common.annotation.LoginCheck;
import common.enums.NoticeScene;
import common.enums.ServiceType;
import common.utils.DateUtil;
import common.utils.Factory;
import common.utils.LoggerUtil;
import common.utils.OrderNoUtil;
import common.utils.PageBean;
import common.utils.ResultInfo;
import common.utils.StrUtil;

import daos.common.CreditorRightDebtDao;

/**
 * 债权债务表service
 * 
 * @author xiaojun
 * @version 2017-4-14 下午4:32:44
 */
public class CreditorRightDebtService extends
		BaseService<t_creditor_right_debt> {

	protected static CommerciaPaperiInfoService commerciaPaperiInfoService = Factory
			.getService(CommerciaPaperiInfoService.class);

	protected static NoticeService noticeService = Factory
			.getService(NoticeService.class);

	protected static CibBankService cibBankService = Factory
			.getService(CibBankService.class);
	private static CreditorRightDebtDao creditorRightDebtDao;

	protected CreditorRightDebtService() {
		creditorRightDebtDao = Factory.getDao(CreditorRightDebtDao.class);
		super.basedao = creditorRightDebtDao;
	}

	protected static CompanyInfoService companyInfoService = Factory
			.getService(CompanyInfoService.class);
	protected static CompanyInfoSideService companyInfoSideService = Factory
			.getService(CompanyInfoSideService.class);
	protected static CityService cityService = Factory
			.getService(CityService.class);

	protected static ReceivablesPushService receivablesPushService = Factory
			.getService(ReceivablesPushService.class);

	protected static UserService userService = Factory
			.getService(UserService.class);
	
	protected static BankListService bankListService = Factory
			.getService(BankListService.class);
	
	/** 合同债权 */
	int is_creditor_right = 0;

	/** 商票债权 */
	int is_creditor_debt = 1;

	/** 债务 */
	int debt = 0;

	/** 债权 */
	int right = 1;

	/**
	 * 后台-风控页面-总合同债权
	 * 
	 * @param currPage
	 *            总页
	 * @param pageSize
	 *            当前页
	 * @param exports
	 *            导出
	 * @param orderType
	 *            排序类型
	 * @param orderValue
	 *            排序
	 * @param full_name
	 *            全称
	 * @param numNo
	 *            编号
	 * @param short_name
	 *            简称
	 *            
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public PageBean<CreditorRight> pageOfCreditorRisk(int showType,int currPage,
			int pageSize, int exports, int orderType, int orderValue,
			String creditorName, String numNo, String debtPersonName  
			) {
		return creditorRightDebtDao.pageOfCreditorRisk(showType,currPage, pageSize,
				exports, orderType, orderValue, creditorName, numNo, debtPersonName);

	}

	/**
	 * 后台-风控页面-合同债权-计算合计债权总金额
	 * 
	 * @param full_name
	 * @param numNo
	 * @param short_name
	 * @param creditor_money
	 * @return
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public double findTotalTicketAmount(int showType,String creditorName, String numNo,
			String debtPersonName, String creditor_money) {

		return creditorRightDebtDao.findTotalTicketAmount(showType,creditorName, numNo, debtPersonName,creditor_money);
	}

	/**
	 * 后台-风控页面-合同债权-债权详情
	 * 
	 * @param showType
	 *            类型0 债权 1 债务
	 * @param company_id
	 * @param currPage
	 * @param pageSize
	 * @param exports
	 * @return
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public PageBean<t_creditor_right_debt> pagetocreditorRight(int showType,
			long company_id, int currPage, int pageSize, int exports) {

		return creditorRightDebtDao.pagetocreditorRight(showType, company_id,
				currPage, pageSize, exports);
	}

	/**
	 * 后台-风控页面-商票债权-债权详情
	 * 
	 * @param showType
	 * @param company_id
	 * @param currPage
	 * @param pageSize
	 * @param exports
	 * @return PageBean<TicketRights>
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public PageBean<TicketRights> pagetoTicketRight(int showType,
			long company_id, int currPage, int pageSize, int exports) {

		return creditorRightDebtDao.pagetoTicketRight(showType, company_id,
				currPage, pageSize, exports);
	}

	/**
	 * 后台-风控页面-商票债权-计算合计债权总金额
	 * 
	 * @param full_name
	 * @param numNo
	 * @param short_name
	 * @param creditor_money
	 * @return double（金额）
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public double findTicketmoney(int showType, long company_id, String crd,
			int is_creditor_right) {

		return creditorRightDebtDao.findTicketmoney(showType, company_id, crd,
				is_creditor_right);
	}

	/**
	 * 后台-风控-商票债权-总金额计算
	 * 
	 * @return
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public PecuniaCredita findCredita(String full_name, String numNo,
			String short_name, int is_creditor_right) {

		return creditorRightDebtDao.findCredita(full_name, numNo, short_name,
				is_creditor_right);
	}

	/**
	 * 前台-挂牌融通-申请额度查询已登记的商票债权信息
	 * 
	 * @param condition
	 *            条件
	 * @param params
	 *            参数数组
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public List<t_creditor_right_debt> findListByCompanyId(long company_id) {

		return creditorRightDebtDao.findListByCompanyId(company_id);

	};

	/**
	 * 前台-挂牌融通-申请额度查询已登记的商票债权信息
	 * 
	 * @param userId
	 *            用户id
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public List<QuotaApplicationBean> findBeanByCompanyId(long userId) {

		return creditorRightDebtDao.findBeanByCompanyId(userId);

	};

	/**
	 * 前台-挂牌融通-申请额度查询已登记的商票债权信息(APP)
	 * 
	 * @param userId
	 *            用户id
	 * @param currPage
	 *            当前页
	 * @param pageSize
	 *            当前页显示数目
	 * @author xiaojun
	 * @createDate 2017年4月19日
	 */
	public PageBean<QuotaApplicationBean> findAPPBeanByCompanyId(long userId,
			int currPage, int pageSize) {
		return creditorRightDebtDao.findAPPBeanByCompanyId(userId, currPage,
				pageSize);
	}

	/**
	 * 挂牌融通-申请融通
	 * 
	 * @param creditor_right_debt
	 *            债权信息
	 * @return
	 * @author xiaojun
	 * @createDate 2017年5月8日
	 */
	public boolean updateStatus(t_creditor_right_debt t) {

		return creditorRightDebtDao.save(t);
	}

	/**
	 * 修改状态
	 * 
	 * @param status
	 * @param olStatus
	 * @param id
	 * @return
	 * @author xiaojun
	 * @version 2018-1-2
	 */
	public boolean updateStatus(int status, int olStatus, long id) {
		return creditorRightDebtDao.updateStatus(status, olStatus, id);
	}

	/**
	 * 前台-账户中心-交易管理-合同债权
	 * 
	 * @param showType
	 *            0 债务 1 债权
	 * @param company_id
	 *            企业用户id
	 * @param currPage
	 * @param pageSize
	 * @param status
	 *            债权状态
	 * @param checkin_time
	 *            开始时间
	 * @param to_checkin_time
	 *            结束时间
	 * @return PageBean<t_creditor_right_debt>
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public PageBean<t_creditor_right_debt> pagetoTontractRight(int showType,
			long company_id, int currPage, int pageSize, int status,
			String checkin_time, String to_checkin_time, int exports) {

		return creditorRightDebtDao.pagetoTontractRight(showType, company_id,
				currPage, pageSize, status, checkin_time, to_checkin_time,
				exports);
	}

	/**
	 * 前台-账户中心-交易管理-合同债权-金额计算
	 * 
	 * @param showType
	 *            0 债权 1 债务
	 * @param company_id
	 *            企业用户user_id
	 * @param type 0 总金额  1，剩余金额
	 * @param crd
	 * @return
	 * @author xiaojun
	 * @createDate 2017年5月8日
	 */
	public double findMoney(int showType, long company_id, int currPage,
			int pageSize, int status, String checkin_time,
			String to_checkin_time, int type) {
		return creditorRightDebtDao.findMoney(showType, company_id, currPage,
				pageSize, status, checkin_time, to_checkin_time,type);

	}

	/**
	 * 前台-账户中心-交易管理-合同债权-操作
	 * 
	 * @param id
	 *            债权id
	 * @param status
	 *            债权状态
	 * @return ResultInfo
	 * @author xiaojun
	 * @version 2017-5-9 下午4:20:42
	 */
	public ResultInfo operationStatus(t_creditor_right_debt t) {
		ResultInfo result = new ResultInfo();

		boolean savefals = creditorRightDebtDao.save(t);
		if (!savefals) {
			result.code = -1;
			result.msg = "操作失败";

			return result;
		}
		result.code = 1;
		result.msg = "操作成功";
		result.obj = t;
		return result;
	}

	/**
	 * 新增商票
	 * 
	 * @param user_id
	 * @param commercialPaperInfo
	 * @param type
	 * @param paper_money
	 * @param bill_code
	 * @param account_num
	 * @param account_bank
	 * @param drawee
	 * @param paper_expire_time
	 * @param paper_create_time
	 * @return
	 * @author xiaojun
	 * @version 2017-8-1
	 */
	/*
	 * public ResultInfo addTicket(long user_id,t_commercial_paper_info
	 * commercialPaperInfo,double paper_money,String bill_code,String
	 * account_num,t_cib_bank cib_bank,String drawee,String
	 * paper_expire_time,String paper_create_time){ //新增商票信息 ResultInfo
	 * result=new ResultInfo(); t_creditor_right_debt creditor_right_debt=
	 * findByID(commercialPaperInfo.debt_creditor_id);
	 * if(creditor_right_debt.company_id == 0){ t_company_info company_info =
	 * companyInfoService
	 * .findCompanyByFullName(creditor_right_debt.creditor_name);
	 * if(company_info == null){ result.code = -1; result.msg =
	 * "债权人不存在！请联系债权人在平台注册！谢谢合作！"; return result; }
	 * creditor_right_debt.company_id = company_info.user_id; }
	 * commercialPaperInfo=commerciaPaperiInfoService.saveTicket(
	 * paper_expire_time,
	 * paper_create_time,commercialPaperInfo,paper_money,bill_code
	 * ,account_num,cib_bank,drawee,creditor_right_debt);
	 * if(commercialPaperInfo.id==null){ LoggerUtil.info(true, "登记商票失败");
	 * result.msg = "登记商票失败"; result.code = -1; return result; } //更新债权表数据
	 * creditor_right_debt.status =
	 * t_creditor_right_debt.CreditorRightDebtStatus.REGISTER.code;
	 * creditor_right_debt.is_creditor_right = 1;
	 * creditor_right_debt.commer_paper_id = commercialPaperInfo.id;
	 * if(Arith.sub(creditor_right_debt.creditor_money,
	 * commercialPaperInfo.paper_money) < 0){ result.msg = "商票金额大于债权债务金额！";
	 * result.code = -1; return result; }
	 * creditor_right_debt.rest_debt_money=creditor_right_debt
	 * .creditor_money-commercialPaperInfo.paper_money;
	 * result=operationStatus(creditor_right_debt); if(result.code<0){
	 * LoggerUtil.info(true, result.msg); return result; } // 添加商票跟踪表信息
	 * t_commercial_paper_record commercialPaperRecord = new
	 * t_commercial_paper_record();
	 * commercialPaperRecord.commer_paper_id=commercialPaperInfo.id;
	 * commercialPaperRecord
	 * .type=t_commercial_paper_record.RecordType.REGISTER.code;
	 * commercialPaperRecord.open_ticket_id=creditor_right_debt.debt_com_id;
	 * commercialPaperRecord.receive_id=creditor_right_debt.company_id;
	 * commercialPaperRecord.operator_id=user_id;
	 * commercialPaperRecord.paper_datetime=new Date(); boolean save=
	 * commerciaPaperRecordService
	 * .saveCommerciaPaperRecord(commercialPaperRecord); if(!save){
	 * LoggerUtil.info(true, "新增商票跟踪表数据异常"); result.msg = "新增商票跟踪表数据异常！";
	 * result.code = -1; return result; } result.msg = "新增商票成功！"; result.code =
	 * 2; return result; }
	 */

	/**
	 * 根据userId和状态查询债权列表
	 * 
	 * @param userId
	 * @param status
	 *            0 待确认1 已取消 2 未确认 3已确认 4 已登记 5 融通中 6 已失效 7未申请
	 * @param type
	 *            0 债务 1 债权
	 * @return
	 * @author zhiliang.lan
	 * @param status
	 * @createDate 2017年5月10日
	 */
	public List<t_creditor_right_debt> findCreditorRightByUserId(long userId,
			int status, int type) {

		return creditorRightDebtDao.findCreditorRightByUserId(userId, status,
				type);
	}

	/**
	 * 根据userId和状态查询债权列表（APP分页）
	 * 
	 * @param userId
	 * @param status
	 *            0 待确认1 已取消 2 未确认 3已确认 4 已登记 5 融通中 6 已失效 7未申请
	 * @param type
	 *            0 债务 1 债权
	 * @return
	 * @author zhiliang.lan
	 * @param status
	 * @createDate 2017年5月10日
	 */
	public PageBean<t_creditor_right_debt> findCreditorRightByUserId(
			long userId, int status, int type, int currPage, int pageSize) {
		return creditorRightDebtDao.findCreditorRightByUserId(userId, status,
				type, currPage, pageSize);
	}

	/**
	 * 根据userId和状态查询债务列表
	 * 
	 * @param userId
	 * @param status
	 * @return
	 * @author zhiliang.lan
	 * @param status
	 * @createDate 2017年5月10日
	 */
	public List<t_creditor_right_debt> findDebtByUserId(long userId, int status) {

		return creditorRightDebtDao.findDebtByUserId(userId, status);
	}

	/**
	 * 新增债务债权
	 * 
	 * @param creditorDebt
	 * @return
	 * @author zhiliang.lan
	 * @createDate 2017年5月10日
	 */
	public boolean addCreditorRightDebt(t_creditor_right_debt creditorDebt) {

		return creditorRightDebtDao.save(creditorDebt);
	}

	/**
	 * 前台-账户中心-交易管理-商票债权列表
	 * 
	 * @param showType
	 *            1 债权 2 债务
	 * @param company_id
	 *            企业用户id
	 * @param currPage
	 * @param pageSize
	 * @param status
	 *            债权状态
	 * @param checkin_time
	 *            开始时间
	 * @param to_checkin_time
	 *            结束时间
	 * @return PageBean<t_creditor_right_debt>
	 * @author xiaojun
	 * @version 2017-5-3 下午7:20:42
	 */
	public PageBean<ReceptionTicketRight> pagetoTicketRight(int showType,
			long company_id, int currPage, int pageSize, int status,
			String checkin_time, String to_checkin_time, int exports) {

		return creditorRightDebtDao.pagetoTicketRight(showType, company_id,
				currPage, pageSize, status, checkin_time, to_checkin_time,
				exports);
	}

	/**
	 * 前台-账户中心-交易管理-商票债权-金额计算
	 * 
	 * @param showType
	 *            0 债权 1 债务
	 * @param company_id
	 *            企业用户user_id
	 * @param crd
	 * @return
	 * @author xiaojun
	 * @createDate 2017年5月8日
	 */
	public double findTicketMoney(int showType, long company_id, int currPage,
			int pageSize, int status, String checkin_time,
			String to_checkin_time) {
		return creditorRightDebtDao.findTicketMoney(showType, company_id,
				currPage, pageSize, status, checkin_time, to_checkin_time);

	}

	/**
	 * 前台-账户中心-商票列表-数字商票转开-查询用户债务信息
	 * 
	 * @param debt_com_id
	 *            债务id
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3
	 */
	public List<t_creditor_right_debt> findtoTontractRight(long debt_com_id,
			double rest_debt_money) {
		return creditorRightDebtDao.findtoTontractRight(debt_com_id,
				rest_debt_money);
	}

	/**
	 * 前台-账户中心-商票列表-数字商票转开-查询用户债务信息-APP
	 * 
	 * @param debt_com_id
	 *            债务id
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3
	 */
	public List<TicketAwayBean> findtoTicketAway(long debt_com_id,
			double rest_debt_money) {
		return creditorRightDebtDao.findtoTicketAway(debt_com_id,
				rest_debt_money);
	}

	/**
	 * 债权债务登记
	 * 
	 * @param type
	 *            0 债务 1债权
	 * @param creditor_name
	 *            债权人名称
	 * @param contact_name
	 *            联系人名称
	 * @param creditor_money
	 *            债权金额
	 * @param contact_mobile
	 *            联系人电话
	 * @param contract_name_code
	 *            合同名称编号
	 * @param contact_addr
	 *            联系人地址
	 * @param contract_datetime
	 *            合同账期（天）
	 * @param contact_email
	 *            联系人邮箱
	 * @param ageing
	 *            账龄（天）
	 * @param statement_time
	 *            结算日期
	 * @param is_creditor_right
	 *            0合同债权 1 商票债权
	 * @param pic_addr_pact
	 *            合同图片
	 * @param pic_addr_bill
	 *            发票图片
	 * @param pic_addr_debt
	 *            出入库单图片
	 * @param pic_addr_bank
	 *            银行流水图片
	 * @param pic_addr_other
	 *            其他资料图片
	 * @param remark
	 *            备注
	 * @param paper_money
	 *            商票金额
	 * @param paper_pic_on
	 *            商票正面
	 * @param paper_pic_under
	 *            商票反面
	 * @param paper_expire_time
	 *            到期时间
	 * @param paper_create_time
	 *            出票时间
	 * @param bill_code
	 *            商票号码
	 * @param drawee
	 *            付款人
	 * @param account_num
	 *            付款人账户
	 * @param account_bank
	 *            付款人开户银行
	 * @author xiaojun
	 * @version 2017-6-8
	 */
	/*
	 * public t_creditor_right_debt addCreditDebt(long crdid,t_company_info
	 * company_info ,t_company_info company,double paper_money,int
	 * is_creditor_right,int type,long user_id,String creditor_name,String
	 * contact_name,double creditor_money,String contact_mobile,String
	 * contract_name_code,String contact_addr, int contract_datetime, String
	 * contact_email, int ageing, String statement_time,String
	 * statement_open_time,String pic_addr_pact,String pic_addr_bill,String
	 * pic_addr_debt,String pic_addr_bank,String pic_addr_other,String remark){
	 * 
	 * t_creditor_right_debt crd = findByID(crdid); if(crd == null){ crd = new
	 * t_creditor_right_debt(); } if(type == 0 ){
	 * crd.company_id=company.user_id; crd.creditor_name=creditor_name;
	 * crd.contact_name=contact_name; crd.contact_mobile=contact_mobile;
	 * crd.contact_addr=contact_addr; crd.contact_email=contact_email;
	 * 
	 * crd.debt_com_id=company_info.user_id;
	 * crd.debt_name=company_info.agent_name;
	 * crd.debt_mobile=company_info.agent_mobile;
	 * crd.debt_contact_name_addr=company_info.agent_address;
	 * crd.debt_person_name=company_info.full_name;
	 * crd.debt_contact_email=company_info.agent_email;
	 * 
	 * }else if(type==1){ crd.debt_com_id=company.user_id;
	 * crd.debt_person_name=creditor_name; crd.debt_name=contact_name;
	 * crd.debt_mobile=contact_mobile; crd.debt_contact_name_addr=contact_addr;
	 * crd.debt_contact_email=contact_email;
	 * 
	 * crd.company_id=company_info.user_id;
	 * crd.creditor_name=company_info.full_name;
	 * crd.contact_name=company_info.agent_name;
	 * crd.contact_mobile=company_info.agent_mobile;
	 * crd.contact_addr=company_info.agent_address;
	 * crd.contact_email=company_info.agent_email;
	 * 
	 * } crd.contract_datetime=contract_datetime;
	 * crd.creditor_money=creditor_money; crd.debt_money=creditor_money;
	 * crd.register_id=user_id; crd.contract_name_code=contract_name_code;
	 * crd.ageing=ageing; crd.statement_time= DateUtil.strToDate(statement_time,
	 * "yyyy/MM/dd"); crd.statement_open_time=
	 * DateUtil.strToDate(statement_open_time, "yyyy/MM/dd"); crd.remark=remark;
	 * crd.checkin_time=new Date(); crd.status =
	 * t_creditor_right_debt.CreditorRightDebtStatus.NOT_APPLY.code;
	 * crd.pic_addr_pact = pic_addr_pact; crd.pic_addr_bill = pic_addr_bill;
	 * crd.pic_addr_debt = pic_addr_debt; crd.pic_addr_bank = pic_addr_bank;
	 * crd.pic_addr_other = pic_addr_other; crd.rest_debt_money =
	 * creditor_money; if(is_creditor_right == 1){ crd.rest_debt_money =
	 * creditor_money-paper_money; if(crd.commer_paper_id == 0){
	 * crd.commer_paper_id = 0; } }else{ crd.commer_paper_id = 0; }
	 * crd.is_creditor_right = is_creditor_right;
	 * 
	 * 
	 * boolean save = addCreditorRightDebt(crd); if(!save){ crd = null; } return
	 * crd; }
	 */
	/**
	 * 申请登记债权债务
	 * 
	 * @param list
	 *            债权债务id集合
	 * @param type
	 *            0 债务 1 债权
	 * @param is_creditor_right
	 *            0合同债权 1 商票债权
	 * @return
	 * @author xiaojun
	 * @version 2017-6-9
	 */
	public boolean updateApplyStatus(List<t_creditor_right_debt> list, int type) {
		List idList = new ArrayList();
		for (t_creditor_right_debt debt : list) {
			idList.add(debt.id);
		}
		return creditorRightDebtDao.updateApplyStatus(list, type);

	}

	/**
	 * 申请登记债权债务
	 * 
	 * @param list
	 *            债权债务id集合
	 * @param type
	 *            0 债务 1 债权
	 * @param is_creditor_right
	 *            0合同债权 1 商票债权
	 * @return
	 * @author xiaojun
	 * @version 2017-6-9
	 */
	public ResultInfo updateApplyStatus2(Long user_id) {

		ResultInfo result = new ResultInfo();
		result.code = 1;
		int save = creditorRightDebtDao.updateApplyStatus2(user_id,
				CreditorRightDebtStatus.CONFIRM.code, is_creditor_right, debt);
		if (save < 0) {
			result.code = -1;
			result.msg = "合同债务申请失败";
		}
		save = creditorRightDebtDao.updateApplyStatus2(user_id,
				CreditorRightDebtStatus.TBC.code, is_creditor_right, right);
		if (save < 0) {
			result.code = -1;
			result.msg = "合同债权申请失败";
		}
		save = creditorRightDebtDao.updateApplyStatus2(user_id,
				CreditorRightDebtStatus.REGISTER.code, is_creditor_debt, right);
		if (save < 0) {
			result.code = -1;
			result.msg = "商票债权申请失败";
		} else if (save > 0) {
			result.code = 2;
		}
		save = creditorRightDebtDao.updateApplyStatus2(user_id,
				CreditorRightDebtStatus.REGISTER.code, is_creditor_debt, debt);
		if (save < 0) {
			result.code = -1;
			result.msg = "商票债务申请失败";
		} else if (save > 0) {
			result.code = 2;
		}

		return result;

	}

	/***
	 * 删除债权债务
	 * 
	 * @param id
	 * @return
	 * @author xiaojun
	 * @version 2017-6-9
	 */
	public boolean deleteCreditDebt(long id) {
		int i = creditorRightDebtDao.delete(id);
		return i == 1 ? true : false;
	}

	/**
	 * 删除图片
	 * 
	 * @param crd
	 * @return
	 * @author xiaojun
	 * @version 2017-7-28
	 */
	/*
	 * public boolean deleteCreditDebtImg(t_creditor_right_debt crd){ boolean
	 * delete = false; if(crd.pic_addr_bank != null){ delete =
	 * DeleteImg.deleteImg(crd.pic_addr_bank); } if(crd.pic_addr_bill != null){
	 * delete = DeleteImg.deleteImg(crd.pic_addr_pact); } if(crd.pic_addr_debt
	 * != null){ delete = DeleteImg.deleteImg(crd.pic_addr_bill); }
	 * if(crd.pic_addr_other != null){ delete =
	 * DeleteImg.deleteImg(crd.pic_addr_other); } if(crd.pic_addr_pact!= null){
	 * delete = DeleteImg.deleteImg(crd.pic_addr_debt); } return delete; }
	 */

	/**
	 * 数据校验
	 * 
	 * @param crdid
	 * @param type
	 * @param creditor_name
	 * @param contact_name
	 * @param creditor_money
	 * @param contact_mobile
	 * @param contract_name_code
	 * @param contact_addr
	 * @param contract_datetime
	 * @param contact_email
	 * @param ageing
	 * @param statement_time
	 * @param is_creditor_right
	 * @param pic_addr_pact
	 * @param pic_addr_bill
	 * @param pic_addr_debt
	 * @param pic_addr_bank
	 * @param pic_addr_other
	 * @param remark
	 * @param paper_money
	 * @param paper_pic_on
	 * @param paper_pic_under
	 * @param paper_expire_time
	 * @param paper_create_time
	 * @param bill_code
	 * @param drawee
	 * @param account_num
	 * @param account_bank
	 * @return
	 * @author xiaojun
	 * @version 2017-6-12
	 */
	public static ResultInfo validate(long crdid, int type,
			String creditor_name, String contact_name, double creditor_money,
			String contact_mobile, String contract_name_code,
			String contact_addr, int contract_datetime, String contact_email,
			int ageing, String statement_time, String statement_open_time,
			int is_creditor_right, String pic_addr_pact, String pic_addr_bill,
			String pic_addr_debt, String pic_addr_bank, String pic_addr_other,
			String remark, double paper_money, String paper_pic_on,
			String paper_pic_under, String paper_expire_time,
			String paper_create_time, String bill_code, String drawee,
			String account_num, String account_bank) {
		ResultInfo result = new ResultInfo();
		if (is_creditor_right != 0 && is_creditor_right != 1) {
			result.code = -1;
			result.msg = "参数不符合要求！";
			return result;
		}
		if (StringUtils.isBlank(creditor_name)) {
			result.code = -1;
			result.msg = "企业全称不能为空";
			return result;
		}
		if (creditor_name.length() > 32) {
			result.code = -1;
			result.msg = "企业全称不能大于32个字符";
			return result;
		}
		if (StringUtils.isBlank(contact_name)) {
			result.code = -1;
			result.msg = "联系人不能为空";
			return result;
		}
		if (contact_name.length() > 32) {
			result.code = -1;
			result.msg = "联系人姓名不能大于32个字符";
			return result;
		}
		if (creditor_money < 0) {
			result.code = -1;
			result.msg = "请输入正确金额";
			return result;
		}
		if (creditor_money > 99999999999D) {
			result.code = -1;
			result.msg = "请输入正确金额";
			return result;
		}
		if (StringUtils.isBlank(contact_mobile)) {
			result.code = -1;
			result.msg = "手机号不能为空";
			return result;
		}
		if (!StrUtil.isMobileNum(contact_mobile)) {
			result.code = -1;
			result.msg = "手机号格式不正确";
			return result;
		}
		if (StringUtils.isBlank(contract_name_code)) {
			result.code = -1;
			result.msg = "合同名称编号不能为空";
			return result;
		}
		if (contract_name_code.length() > 128) {
			result.code = -1;
			result.msg = "合同名称编号不能大于128个字符";
			return result;
		}
		if (StringUtils.isBlank(contact_addr)) {
			result.code = -1;
			result.msg = "联系人地址不能为空";
			return result;
		}
		if (contact_addr.length() > 64) {
			result.code = -1;
			result.msg = "联系人地址不能大于64个字符";
			return result;
		}
		if (StringUtils.isBlank(contract_datetime + "")) {
			result.code = -1;
			result.msg = "账期不能为空";
			return result;
		}
		if (contract_datetime > 365) {
			result.code = -1;
			result.msg = "账期最多为365天";
			return result;
		}
		if (StringUtils.isBlank(contact_email)) {
			result.code = -1;
			result.msg = "联系人邮箱不能为空";
			return result;
		}
		if (contact_email.length() > 32) {
			result.code = -1;
			result.msg = "联系人邮箱不能大于32个字符";
			return result;
		}
		if (StringUtils.isBlank(ageing + "")) {
			result.code = -1;
			result.msg = "账龄不能为空";
			return result;
		}
		if (contract_datetime < ageing) {
			result.code = -1;
			result.msg = "账龄不能大于账期";
			return result;
		}
		if (StringUtils.isBlank(statement_time)) {
			result.code = -1;
			result.msg = "结算结束日期不能为空";
			return result;
		}
		if (!StrUtil.is_date(statement_time)) {
			result.code = -1;
			result.msg = "结算结束日期格式不正确";
			return result;
		}
		if (StringUtils.isBlank(statement_open_time)) {
			result.code = -1;
			result.msg = "结算开始日期不能为空";
			return result;
		}
		if (!StrUtil.is_date(statement_open_time)) {
			result.code = -1;
			result.msg = "结算开始日期格式不正确";
			return result;
		}
		if ((new Date().after(DateUtil.strToDate(statement_time, "yyyy/MM/dd")))) {
			result.code = -1;
			result.msg = "结算日期不能在当前时间之前";
			return result;
		}
		if (DateUtil.strToDate(statement_open_time, "yyyy/MM/dd").after(
				DateUtil.strToDate(statement_time, "yyyy/MM/dd"))) {
			result.code = -1;
			result.msg = "结算结束日期不能在开始日期之前";
			return result;
		}
		if (StringUtils.isBlank(remark) || remark.length() > 300
				|| remark.length() < 5) {
			result.code = -1;
			result.msg = "备注建议为 5~300个字符之间";
			return result;
		}

		// 四张图片校验
		if (StringUtils.isBlank(pic_addr_pact)) {
			result.code = -1;
			result.msg = "请上传合同";
			return result;
		}
		if (StringUtils.isBlank(pic_addr_bill)) {
			result.code = -1;
			result.msg = "请上传发票";
			return result;
		}
		if (StringUtils.isBlank(pic_addr_debt)) {
			result.code = -1;
			result.msg = "请上传出入库单";
			return result;
		}
		if (StringUtils.isBlank(pic_addr_bank)) {
			result.code = -1;
			result.msg = "请上传银行流水";
			return result;
		}
		if (is_creditor_right == 1) {

			if (paper_money <= 0) {
				result.code = -1;
				result.msg = "请输入商票金额";
				return result;
			}
			if (paper_money > creditor_money) {
				result.code = -1;
				result.msg = "商票金额不能大于债权债务金额！";
				return result;
			}
			if (StringUtils.isBlank(paper_pic_on)
					|| StringUtils.isBlank(paper_pic_under)) {
				result.code = -1;
				result.msg = "请上传商票图片";
				return result;
			}
			if (StringUtils.isBlank(bill_code)) {
				result.code = -1;
				result.msg = "商票号码不能为空";
				return result;
			}
			if (bill_code.length() > 32) {
				result.code = -1;
				result.msg = "商票号码长度不能大于32个字符";
				return result;
			}
			if (StringUtils.isBlank(paper_create_time)) {
				result.code = -1;
				result.msg = "出票时间不能为空";
				return result;
			}
			if (!StrUtil.is_date(paper_create_time)) {
				result.code = -1;
				result.msg = "出票时间格式不正确";
				return result;
			}
			if (StringUtils.isBlank(paper_expire_time)) {
				result.code = -1;
				result.msg = "商票到期时间不能为空";
				return result;
			}
			if (!StrUtil.is_date(paper_expire_time)) {
				result.code = -1;
				result.msg = "商票到期时间格式不正确";
				return result;
			}

			if (DateUtil.isDateBefore(
					DateUtil.strToDate(paper_expire_time, "yyyy/MM/dd"),
					DateUtil.strToDate(paper_create_time, "yyyy/MM/dd"))) {
				result.code = -1;
				result.msg = "商票到期时间不能再商票出票时间之前";
				return result;
			}
			if (DateUtil.isDateBefore(
					DateUtil.strToDate(paper_expire_time, "yyyy/MM/dd"),
					new Date())) {
				result.code = -1;
				result.msg = "商票到期时间不能小于当前日期";
				return result;
			}
			if (StringUtils.isBlank(drawee)) {
				result.code = -1;
				result.msg = "出票人不能为空";
				return result;
			}
			if (drawee.length() > 32) {
				result.code = -1;
				result.msg = "出票人名称过长";
				return result;
			}
			if (StringUtils.isBlank(account_num)) {
				result.code = -1;
				result.msg = "开户账号不能为空";
				return result;
			}
			if (account_num.length() > 24 || account_num.length() < 9) {
				result.code = -1;
				result.msg = "请填写正确的开户账户";
				return result;
			}
			if (StringUtils.isBlank(account_bank)) {
				result.code = -1;
				result.msg = "开户银行不能为空";
				return result;
			}
		}
		return result;

	}

	/**
	 * 新注册用户登记债务id
	 * 
	 * @param name
	 *            企业全称
	 * @param id
	 *            用户user_id
	 * @return
	 * @author xiaojun
	 * @version 2017-9-29
	 */
	public void setCompanyId(String name, long id) {
		creditorRightDebtDao.setCompanyId(name, id);
		creditorRightDebtDao.setDebtComId(name, id);
	}

	/**
	 * 批量导入账款信息，保存到债权债务表
	 * 
	 * @param list
	 *            excel工具类将表格数据解析成一行
	 * @param type
	 *            类型 0 应付账款 1 应收账款
	 * @return
	 * @author LiangQiongfeng
	 * @version 2018-1-11
	 * @param user
	 *            当前用户
	 */
	public ResultInfo save(List<String[]> list, CurrUser user, int type) {
		
		ResultInfo result = new ResultInfo();
		t_company_info company = null;
		boolean flag = false;
		
		List<t_creditor_right_debt> creditList = new ArrayList<t_creditor_right_debt>();
		
		if (user != null && user.is_company == 1) {
			company = companyInfoService.findCompanyInfoByUserId(user.id);

		}

		/**
		 * 查询出用户的省市地址
		 */
		String city = null;
		String province = null;
		if (company != null) {// 采用数据库中的t_city
			city = cityService.findCity(company.city_id, company.province_id);
			province = cityService.findProvince(company.province_id);
		}
		// 如果文件内容为空，直接返回
		if (list.size() < 1) {
			result.code = -1;
			result.msg = "文件内容不能为空！";
			return result;
		}
		for (String[] str : list) {
			t_creditor_right_debt creditorRight = new t_creditor_right_debt();
			Field[] fields = creditorRight.getClass().getFields();
			// 获取到每一行的数据
			for (int i = 0; i < str.length; i++) {
				// 获取到每一单元格的数据
				try {
					if (!str[i].equals("-1")) {
						fields[i].set(creditorRight, conver(fields[i], str[i]));
					}
				} catch (Exception e) {
					continue;
				}

			}
			t_company_info debt = null;
			
			if (creditorRight != null && StringUtils.isNotBlank(creditorRight.debt_person_name )) {
				debt = companyInfoService.findByCompanyName(creditorRight.debt_person_name);
				
				if (type == 0 && company != null) {// 登记的是应付账款信息，即我本人是债务人
					/** 债权人全称 */
					creditorRight.creditor_name = creditorRight.debt_person_name;
	
					/** 债权统一信用代码（三证合一） */
					creditorRight.creditor_business_license_code = creditorRight.debt_business_license_code;
	
					/** 债权人所在的省 */
					creditorRight.creditor_province = creditorRight.creditor_province;
	
					/** 债权人所在的市 */
					creditorRight.creditor_city = creditorRight.creditor_city;
	
					/** 债权人所在的区 */
					creditorRight.creditor_county = creditorRight.creditor_county;
	
					/**如果名称查询到会员，将其会员id作为债权人公司id*/
					if(debt != null){
						creditorRight.company_id = debt.user_id;
					}
	
					/** 债务人全称 */
					creditorRight.debt_person_name = company.full_name;
	
					/** 债务企业统一信用代码（三证合一） */
					creditorRight.debt_business_license_code = company.business_license_code;
	
					/** 债务人所在的省t_pay_pro_city */
					creditorRight.debt_province = province;
	
					/** 债务人所在的市 */
					creditorRight.debt_city = city;
	
					/** 债务人所在的区 */
					creditorRight.debt_county = null;
	
					creditorRight.debt_com_id = company.user_id;// 债务人id
					
					creditorRight.status = t_creditor_right_debt.CreditorRightDebtStatus.CONFIRM.code;// 状态
					
					creditorRight.type = type;
	
				}
				/**
				 * 由于解析数据表格获得的是从上往下排的字段名和从左往右的单元格数据一一匹配（有19个单元格，对应19个字段）
				 * 而债务人相关数据就在第十九个字段里面，当账款类型为债权账款时，需要修改数据
				 */
				if (type == 1 && company != null) {// 登记应收账款信息，债权人是我
					/** 债权人全称 */
					creditorRight.creditor_name = company.full_name;
	
					/** 债权统一信用代码（三证合一） */
					creditorRight.creditor_business_license_code = company.business_license_code;
	
					/** 债权人所在的省t_pay_pro_city */
					creditorRight.creditor_province = province;
	
					/** 债权人所在的市 */
					creditorRight.creditor_city = city;
	
					/** 债权人所在的区 */
					creditorRight.creditor_county = null;
	
					creditorRight.company_id = company.user_id;// 债权人id
					
					/**如果名称查询到会员，将其会员id作为债权人公司id*/
					if(debt != null){
						creditorRight.debt_com_id = debt.user_id;
						
					}
					creditorRight.status = t_creditor_right_debt.CreditorRightDebtStatus.TBC.code;// 状态
					creditorRight.type = type;
	
				}
				
				// 每遍历完一行，即得到一个对象
				if (creditorRight != null) {
					
					creditorRight.checkin_time = new Date();// 登记时间
					creditorRight.platform_account_code = OrderNoUtil
							.getNormalOrderNo(ServiceType.PLATFORM_ACCOUNT, "");// 平台账款编码
	
					creditorRight.register_id = company.user_id;// 登记人id(当前用户)
					creditorRight.creditor_right_id = 1L;// 当前账款id
					creditorRight.rest_debt_money = creditorRight.creditor_money;// 剩余账款金额
					// creditorRight.lender_id = 1L;//放款人id
	
					
					result = toValida(creditorRight,user);
					
					if (result.code > 0) {//校验通过即进行保存
						flag = creditorRightDebtDao.save(creditorRight);
					}else{//校验出错
						continue;
					}
					if (!flag) {//保存失败
						continue;
					} else {
						
						// 数据保存成功，即进行消息通知
						Map<String, Object> parame = new HashMap<String, Object>();
						
						Map<String, String> userEventParam = new HashMap<String, String>();
						userEventParam.put("userName", user.company_full_name);
						userEventParam.put("ip",Request.current().remoteAddress.toString());
						
						if (type == 1 && creditorRight != null && creditorRight.debt_com_id > 0) {
							parame.put("user_name", creditorRight.debt_person_name);// 需要确认债务的债务企业
							parame.put("company", creditorRight.creditor_name);// 登记债权的债务企业
							parame.put("contract_num",
									creditorRight.contract_num);// 登记债权的合同编号
							parame.put("creditor_money",
									creditorRight.creditor_money);// 登记债权的债务企业
							noticeService.sendSysNotice(creditorRight.debt_com_id,
									NoticeScene.CREDITOR_INFOR_REGIST_OK, parame);
							
							
							userService.addUserEvent(user.id, t_event_user.Event.REGISTER_RECEIVABLE_INFO, userEventParam);
							
						}
						if (type == 0){
							
							userService.addUserEvent(user.id, t_event_user.Event.REGISTER_PAYABLE_INFO, userEventParam);
							
						}
					}
				}
			}else{
				continue;
			}
			creditList.add(creditorRight);
		}
		if(creditList.size() == 0){
			result.code = -1;
			result.msg = "文件内容为空！";
			return result;
		}
		
		// 所有账款信息数据保存成功
		result.code = 2;
		result.msg = "账款信息数据保存成功";
	
		return result;
	}

	/**
	 *	检测当前表格账款序号是否重复
	 * @param creditList
	 * @return
	 * @author LiangQiongfeng
	 *@version 2018-2-4 
	 */
	private ResultInfo checkInvoiceNum(List<t_creditor_right_debt> creditList) {
		ResultInfo result = new ResultInfo();
		List<String> list = new ArrayList<String>();
		String temp ="";
		int count = 0;
		
		for (t_creditor_right_debt creditor : creditList) {
			if(!list.contains(creditor.invoice_num)){
				list.add(creditor.invoice_num);
			}else if((count + 1) < creditList.size()){
				temp += creditor.invoice_num + ",";
			}else{
				temp += creditor.invoice_num;
			}
			count ++;
		}
		if(list.size() != creditList.size()){
			result.code = -1;
			result.msg = "登记表中有发票号码重复,重复发票号码为"+temp;
			return result;
		}
		for (t_creditor_right_debt creditor : creditList) {
			t_creditor_right_debt creditor_right_debt = creditorRightDebtDao.findByColumn("invoice_num = ?", creditor.invoice_num);
			if(creditor_right_debt != null){
				result.code = -1;
				result.msg = "该发票号码"+creditor.invoice_num+"的账款信息已被登记";
				return result;
			}
		}
		result.code = 1;
		result.msg = "校验通过";
		return result;
	}

	/**
	 * 账款信息参数的校验
	 * 
	 * @param debt
	 *            封装到债权债务表中的单元格一行数据
	 * @return
	 * @author LiangQiongfeng
	 * @version 2018-1-15
	 * @param user 
	 */
	private ResultInfo toValida(t_creditor_right_debt debt, CurrUser user) {
		ResultInfo result = new ResultInfo();
		
		if(debt == null){
			result.code = -1;
			result.msg = "请输入账款信息";
			return result;
		}
		
		if (StringUtils.isBlank(debt.debt_person_name)) {
			result.code = -1;
			result.msg = "账款债权/债务人名称不能为空";
			return result;
		}
		if (debt != null && (debt.debt_person_name).equals(debt.creditor_name) ) {
			result.code = -1;
			result.msg = "企业会员不可以既是债权人，又是债务人";
			return result;
		}
		
		if ( StringUtils.isNotBlank(debt.debt_business_license_code)) {
			boolean flag = false;
			if (debt.debt_business_license_code.length() == 15
					|| debt.debt_business_license_code.length() == 18) {
				flag = true;
			}
			if (!flag) {
				result.code = -1;
				result.msg = "账款债务人社会统一信用码不正确，其长度应为15位或者18位";
				return result;
			}
			
		}
		if ( StringUtils.isNotBlank(debt.creditor_business_license_code)) {
			boolean flag = false;
			if (debt.creditor_business_license_code.length() == 15
					|| debt.creditor_business_license_code.length() == 18) {
				flag = true;
			}
			if (!flag) {
				result.code = -1;
				result.msg = "账款债权人社会统一信用码不正确，其长度应为15位或者18位";
				return result;
			}
			
		}
		if (StringUtils.isBlank(debt.debt_province)) {
			result.code = -1;
			result.msg = "省份地址不能为空";
			return result;
		}
		if (StringUtils.isBlank(debt.contract_num)) {
			result.code = -1;
			result.msg = "合同编号不能为空";
			return result;
		}
		if (StringUtils.isBlank(debt.invoice_num)) {
			result.code = -1;
			result.msg = "发票号码不能为空";
			return result;
		}
		if (debt.creditor_money < 0 ) {
			result.code = -1;
			result.msg = "账款金额不能为负数!";
			return result;
		}

		// 校验通过
		result.code = 2;
		result.msg = "校验通过";
		return result;
	}
	/**
	 * 账款信息参数的校验
	 * 
	 * @param debt
	 *            封装到债权债务表中的单元格一行数据
	 * @return
	 * @author LiangQiongfeng
	 * @version 2018-1-15
	 * @param user 
	 */
	private ResultInfo batchToValida(t_creditor_right_debt debt, CurrUser user) {
		ResultInfo result = new ResultInfo();
		
		if(debt == null){
			result.code = -1;
			result.msg = "请输入账款信息";
			return result;
		}
		
		if (StringUtils.isBlank(debt.contract_name_code)) {
			result.code = -1;
			result.msg = "账款序号不能为空";
			return result;
		}
		if (StringUtils.isBlank(debt.debt_person_name)) {
			result.code = -1;
			result.msg = "账款债权/债务人名称不能为空";
			return result;
		}
		if (debt != null && user.company_full_name.equals(debt.debt_person_name) ) {
			result.code = -1;
			result.msg = "企业会员不可以既是债权人，又是债务人";
			return result;
		}
		if (debt != null && user.company_full_name.equals(debt.creditor_name)) {
			result.code = -1;
			result.msg = "企业会员不可以既是债权人，又是债务人";
			return result;
		}
		
		if ( StringUtils.isNotBlank(debt.debt_business_license_code)) {
			boolean flag = false;
			if (debt.debt_business_license_code.length() == 15
					|| debt.debt_business_license_code.length() == 18) {
				flag = true;
			}
			if (!flag) {
				result.code = -1;
				result.msg = "账款债权/债务人社会统一信用码不正确，其长度应为15位或者18位";
				return result;
			}
			
		}
		if (StringUtils.isBlank(debt.debt_province)) {
			result.code = -1;
			result.msg = "省份地址不能为空";
			return result;
		}
		if (StringUtils.isBlank(debt.contract_num)) {
			result.code = -1;
			result.msg = "合同编号不能为空";
			return result;
		}
		if (StringUtils.isBlank(debt.invoice_num)) {
			result.code = -1;
			result.msg = "发票号码不能为空";
			return result;
		}
		if (debt.creditor_money < 0 ) {
			result.code = -1;
			result.msg = "账款金额不能为负数!";
			return result;
		}
		
		// 校验通过
		result.code = 2;
		result.msg = "校验通过";
		return result;
	}

	/**
	 * 单元格数据类型转换
	 * 
	 * @param field
	 *            t_creditor_right_debt 表的属性
	 * @param cell
	 *            单元格内容
	 * @return
	 * @author LiangQiongfeng
	 * @version 2018-1-11
	 * @throws ParseException
	 */
	private Object conver(Field field, String cell) throws ParseException {
		// 当前字段的数据类型
		String type = field.getType().getName();
		// String[] types =
		// {"int","long","double","java.util.Date","java.lang.String"};
		if (type.equals("int")) {
			int toInt = Convert.strToInt(cell, 0);

			return toInt;
		}
		if (type.equals("long")) {
			long toLong = Convert.strToLong(cell, 0);

			return toLong;
		}
		if (type.equals("double")) {
			if(cell.contains(",")){
				cell = cell.replace(",", "");
			}
			double toDouble = Convert.strToDouble(cell, 0.0);

			return toDouble;
		}
		if (type.equals("java.util.Date")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date parse = sdf.parse(cell);
			return parse;
		}
		if (type.equals("java.lang.String")) {
			return Convert.strToStr(cell, "");
		}
		return Convert.strToStr(cell, "");
	}

	/**
	 * 分页查询账款信息
	 * 
	 * @param currPage
	 * @param pageSize
	 * @param lenderId
	 *            放款人id
	 * @param userId
	 *            用户id
	 * @author fanghanyong
	 * @createDate 2018年01月12日
	 * @return
	 */
	public PageBean<t_creditor_right_debt> pageOfCreditorRightDebt(
			int currPage, int pageSize, long lenderId, long userId) {
		return creditorRightDebtDao.pageOfCreditorRightDebt(currPage, pageSize,
				lenderId, userId);
	}

	/**
	 * 查询账款信息
	 * 
	 * @param lenderId
	 *            放款人id
	 * @param userId
	 *            用户id
	 * @author fanghanyong
	 * @createDate 2018年01月12日
	 */
	public List<t_creditor_right_debt> findByUserIdLenderId(long lenderId,
			long userId) {

		return creditorRightDebtDao.findByUserIdLenderId(lenderId, userId);

	}


	/**
	 * 查询账款信息-联表查询
	 * 
	 * @param lenderId
	 *            放款人的ID
	 * @param userId
	 *            融通人的
	 * @param creditId
	 *            授信申请
	 * @author fanghanyong
	 * @createDate 2018年01月12日
	 */
	public List<CreditorRightDebt> findByCreditUserIdLenderId(long lenderId,
			long userId, long creditId) {

		return creditorRightDebtDao.findByCreditUserIdLenderId(lenderId,
				userId, creditId);

	};

	/**
	 * 分页查询 账款登记表-联表查询
	 * 
	 * @param lenderId
	 *            放款人id
	 * @param userId
	 *            申请人id
	 * @param id
	 *            授信id
	 * @return
	 * @author fanghanyong
	 * @createDate 2018年01月12日
	 */
	public CreditorRightDebt findByCreditANDUserIdLenderId(long lenderId, long userId, long creditId) {
		return creditorRightDebtDao.findByCreditANDUserIdLenderId(lenderId, userId, creditId);
	}

	/**
	 * 分页查询 账款登记表-联表查询-总金额
	 * 
	 * @param lenderId
	 *            放款人id
	 * @param userId
	 *            申请人id
	 * @param id
	 *            授信id
	 * @param showType
	 *            状态 0 默认 1 推送中 2 已确认 3 退回
	 * @param code
	 *            账款序号
	 * @param debtName
	 *            债务人
	 * @return
	 * @author fanghanyong
	 * @createDate 2018年01月12日
	 */
	public double totalCreditUserIdLenderId(long lenderId, long userId,
			long creditId, int status, String code, String debtName) {

		return creditorRightDebtDao.totalCreditUserIdLenderId(lenderId, userId,
				creditId, status, code, debtName);
	}

	/**
	 * 
	 * @param applyUserId
	 *            融通人用户ID
	 * @param receiverUserId
	 *            账款ID
	 * @param dirCreditStatus
	 *            账款目标状态，0 默认 1 推送中 2 已确认 3 退回
	 * @param srcCreditStatus
	 *            账款原状态，0 默认 1 推送中 2 已确认 3 退回
	 * @param srcDebtStatus
	 *            账款记录的状态 0 待确认\r\n1 已取消 \r\n2 未确认 \r\n3 已确认 \r\n4 已登记 \r\n5 融通中
	 *            \r\n6 已失效 \r\n7未申请 *
	 * @param dirDebtStatus
	 *            账款记录的状态 0 待确认\r\n1 已取消 \r\n2 未确认 \r\n3 已确认 \r\n4 已登记 \r\n5 融通中
	 *            \r\n6 已失效 \r\n7未申请
	 * @param userId
	 *            放款人的
	 * @param contractNameCode
	 *            账款序号
	 * @author fanghanyong
	 * @version 2018-1-16
	 * @return
	 */
	@LoginCheck
	public static ResultInfo updatePushDebt(long applyUserId,
			long receiverUserId, int dirCreditStatus, int srcCreditStatus,
			int srcDebtStatus, int dirDebtStatus, long userId,
			String contractNameCode) {
		ResultInfo result = new ResultInfo();
		// 判断账款状态是否是已确认，并且想要进行绑定
		if (srcDebtStatus != 3 && dirCreditStatus == 2) {
			result.code = -1;
			result.msg = "账款记录状态不符合，不能被绑定";
			return result;
		}
		
		t_creditor_right_debt creditor_right_debt = creditorRightDebtDao.findByID(receiverUserId);
		
		//如果应付账款已经进行过转开，不允许绑定授信申请
		if(srcCreditStatus == 1 && creditor_right_debt.creditor_money != creditor_right_debt.rest_debt_money && dirCreditStatus == 2){
			result.code = -1;
			result.msg = "账款已使用，不能被绑定,请退回该账款";
			return result;
		}
		// 更新推送表的状态信息
		int updatePushCount = receivablesPushService
				.updateReceivablesPushStatus(applyUserId, receiverUserId,
						dirCreditStatus, srcCreditStatus, userId);
		if (updatePushCount <= 0) {
			LoggerUtil.error(true, "更改表t_receivables_push状态失败");
			result.code = -1;
			result.msg = "更新表状态失败";
			return result;
		}
		// 如果是退回，则原状态和放款人不变,如果是绑定操作，则原状态和放款人的ID更新
		boolean updateDebtFlag = true;
		if (dirCreditStatus == 2) {
			// 更新账款表的信息
			updateDebtFlag = creditorRightDebtDao.updateStatusLeaderId(
					dirDebtStatus, srcDebtStatus, receiverUserId, userId);
		}
		if (!updateDebtFlag) {
			LoggerUtil.error(true, "更改表t_creditor_right_debt状态失败");
			result.code = -1;
			result.msg = "更新表状态失败";
			return result;
		}

		result.code = 1;
		result.msg = "绑定成功";
		return result;

	}

	/**
	 * 修改状态
	 * 
	 * @param status
	 *            目标状态ID
	 * @param olStatus
	 *            原状态ID
	 * @param id
	 *            账款
	 * @param leaderId
	 *            放款人
	 * @return
	 * @author fanghanyong
	 * @version 2018-01-16
	 */
	public boolean updateStatusLeaderId(int status, int olStatus, long id,
			long leaderId) {
		return creditorRightDebtDao.updateStatusLeaderId(status, olStatus, id,
				leaderId);
	}

	/**
	 * 定时任务 标记债权债务失效
	 * 
	 * @return
	 * @author xiaojun
	 * @version 2017-5-3
	 */
	public ResultInfo systemDebtMarkFailure() {
		return creditorRightDebtDao.autoDebtMarkFailure();

	}

	/**
	 *	数据校验
	 * @param list
	 * @return
	 * @author LiangQiongfeng
	 *@version 2018-2-6 
	 * @param user 
	 */
	public ResultInfo checkCredit(List<String[]> list, CurrUser user) {
		ResultInfo result = new ResultInfo();
		List<t_creditor_right_debt> creditList = new ArrayList<t_creditor_right_debt>();
		for (String[] str : list) {
			t_creditor_right_debt creditorRight = new t_creditor_right_debt();
			Field[] fields = creditorRight.getClass().getFields();
			// 获取到每一行的数据
			for (int i = 0; i < str.length; i++) {
				// 获取到每一单元格的数据
				try {
					if (!str[i].equals("-1")) {
						fields[i].set(creditorRight, conver(fields[i], str[i]));
					}
				} catch (Exception e) {
					continue;
				}

			}
			result = batchToValida(creditorRight,user);
			creditList.add(creditorRight);
		}
		if(result.code < 0){
			return result;
		}
		if(creditList.size() == 0){
			// 所有账款信息数据校验成功
			result.code = -1;
			result.msg = "文件内容为空！";
			return result;
		}
		
		//当前发票号码校验(一票一号一笔)
		result = checkInvoiceNum(creditList);
		if(result.code < 0){
			return result;
		}
		return result;
	}

	/**
	 *	融资项目展示
	 * @param creditorNum
	 * @return
	 * @author Liangqiongfeng
	 *@version 2018-2-10 
	 */
	public List<t_creditor_right_debt> findListBySQL() {
		
		return creditorRightDebtDao.findListBySQL();
	}
	/**
	 *	融资项目展示 微信
	 * @param creditorNum
	 * @return
	 * @author Liangqiongfeng
	 *@version 2018-2-10 
	 */
	public PageBean<Map<String, Object>> findMapByHome(int currPage, int pageSize) {
		
		return creditorRightDebtDao.findMapByHome(currPage, pageSize);
	}

	/**
	 * 改变账款剩余额度
	 * @param creditorRightDebt
	 * @return
	 * @author liangqiongfeng
	 *@version 2018-3-22 
	 */
	public boolean updateCreditor(t_creditor_right_debt creditorRightDebt) {
		
		return creditorRightDebtDao.updateCreditor(creditorRightDebt);
	}

	public PageBean<t_creditor_right_debt> pagetoTontractRight(int showType,
			long company_id, int currPage, int pageSize, int status) {

		return creditorRightDebtDao.pagetoTontractRight(showType, company_id,
				currPage, pageSize, status);
	}

	public double findMoney(int showType, long company_id, int currPage,
			int pageSize, int status, int type) {
		return creditorRightDebtDao.findMoney(showType, company_id, currPage,
				pageSize, status,type);
	}
	
	
	/**
	 * 微信登记账款
	 * @param type 0 应付 1 应收
	 * @param contract_name_code 账款编号
	 * @param creditor_name 债权人名称
	 * @param creditor_business_license_code 债权人组织机构代码
	 * @param creditor_province债权人所属省
	 * @param debt_person_name 债务人名称
	 * @param debt_business_license_code债务人组织机构代码
	 * @param debt_province债务人所属省
	 * @param remark 账款描述
	 * @param contract_num 合同号	
	 * @param invoice_num 发票号
	 * @param creditor_money 账款金额
	 * @param currency 币种
	 * @param voucher_remark 备注
	 */
	public ResultInfo validateWX(int type, String contract_name_code,
			String creditor_name, String creditor_business_license_code,
			String creditor_province, String debt_person_name,
			String debt_business_license_code, String debt_province,
			String remark, String contract_num,
			String invoice_num, double creditor_money, String currency,
			String voucher_remark) {
		
		ResultInfo result = new ResultInfo();
		
		if(type == 0){
			if (StringUtils.isBlank(creditor_name)) {
				result.code = -1;
				result.msg = "账款债权人名称不能为空";
				return result;
			}
			
			if ( StringUtils.isNotBlank(creditor_business_license_code)) {
				boolean flag = false;
				if (creditor_business_license_code.length() == 15
						|| creditor_business_license_code.length() == 18) {
					flag = true;
				}
				if (!flag) {
					result.code = -1;
					result.msg = "账款债权人社会统一信用码不正确，其长度应为15位或者18位";
					return result;
				}
				
			}
			if (StringUtils.isBlank(creditor_province)) {
				result.code = -1;
				result.msg = "省份地址不能为空";
				return result;
			}
		}else{

			
			if (StringUtils.isBlank(debt_person_name)) {
				result.code = -1;
				result.msg = "账款债务人名称不能为空";
				return result;
			}
			
			if ( StringUtils.isNotBlank(debt_business_license_code)) {
				boolean flag = false;
				if (debt_business_license_code.length() == 15
						|| debt_business_license_code.length() == 18) {
					flag = true;
				}
				if (!flag) {
					result.code = -1;
					result.msg = "账款债务人社会统一信用码不正确，其长度应为15位或者18位";
					return result;
				}
				
			}
			if (StringUtils.isBlank(debt_province)) {
				result.code = -1;
				result.msg = "省份地址不能为空";
				return result;
			}
			
		}

		if (StringUtils.isBlank(contract_name_code)) {
			result.code = -1;
			result.msg = "账款序号不能为空";
			return result;
		}
		
		if (StringUtils.isBlank(contract_num)) {
			result.code = -1;
			result.msg = "合同编号不能为空";
			return result;
		}
		
		if (StringUtils.isBlank(invoice_num)) {
			result.code = -1;
			result.msg = "发票号码不能为空";
			return result;
		}
		//TODO
		int count = creditorRightDebtDao.countByColumn(" invoice_num = ?", invoice_num);
		if(count > 0){
			result.code = -1;
			result.msg = "发票号码"+invoice_num+"已被登记";
			return result;
		}
		if (creditor_money < 0 ) {
			result.code = -1;
			result.msg = "账款金额不能为负数!";
			return result;
		}
		
		// 校验通过
		result.code = 2;
		result.msg = "校验通过";
		return result;
	}
	
	/**
	 * 微信登记账款保存
	 * @param company_info 当前用户企业信息
	 * @param type 0 应付 1 应收
	 * @param contract_name_code 账款编号
	 * @param creditor_name 债权人名称
	 * @param creditor_business_license_code 债权人组织机构代码
	 * @param creditor_province债权人所属省
	 * @param debt_person_name 债务人名称
	 * @param debt_business_license_code债务人组织机构代码
	 * @param debt_province债务人所属省
	 * @param remark 账款描述
	 * @param contract_num 合同号	
	 * @param invoice_num 发票号
	 * @param creditor_money 账款金额
	 * @param currency 币种
	 * @param voucher_remark 备注
	 */
	public ResultInfo saveCreditor(t_company_info company_info, int type,
			String contract_name_code, String creditor_name,
			String creditor_business_license_code, String creditor_province,
			String debt_person_name, String debt_business_license_code,
			String debt_province, String remark, String contract_num,
			String invoice_num, double creditor_money, String currency,
			String voucher_remark) {
		
		ResultInfo result = new ResultInfo();
		
		t_creditor_right_debt creditor = new t_creditor_right_debt();
		
		t_company_info findCompany = null;
		
		if(type == 1){
			findCompany = companyInfoService.findCompanyByFullName(debt_person_name);
		}else{
			findCompany = companyInfoService.findCompanyByFullName(creditor_name);
		}
		
		creditor.checkin_time = new Date();// 登记时间
		creditor.platform_account_code = OrderNoUtil
				.getNormalOrderNo(ServiceType.PLATFORM_ACCOUNT, "");// 平台账款编码

		creditor.register_id = company_info.user_id;// 登记人id(当前用户)
		creditor.creditor_right_id = 1L;// 当前账款id
		creditor.remark = remark;
		creditor.contract_num = contract_num;
		creditor.invoice_num = invoice_num;
		creditor.creditor_money = creditor_money;
		creditor.voucher_remark = voucher_remark;
		creditor.currency =currency;
		creditor.contract_name_code = contract_name_code;
		creditor.rest_debt_money = creditor_money;// 剩余账款金额
		if(type == 1){
			creditor.company_id = company_info.user_id;
			creditor.creditor_name = company_info.full_name;
			creditor.creditor_business_license_code = company_info.business_license_code;
			creditor.creditor_province = company_info.address;
			creditor.debt_person_name =debt_person_name;
			
			creditor.debt_business_license_code = debt_business_license_code;

			if(findCompany == null){
				creditor.debt_com_id = 0;
				creditor.debt_province =debt_province;
			}else{
				creditor.debt_com_id =findCompany.user_id;
				creditor.debt_province =findCompany.address;
				
			}
			
			creditor.status = t_creditor_right_debt.CreditorRightDebtStatus.TBC.code;
			
		}
		if(type == 0){
			creditor.debt_com_id = company_info.user_id;
			
			creditor.debt_person_name = company_info.full_name;
			creditor.debt_business_license_code = company_info.business_license_code;
			creditor.debt_province = company_info.address;
			creditor.creditor_name =creditor_name;
			
			creditor.creditor_business_license_code = debt_business_license_code;
			
			
			if(findCompany == null){
				creditor.company_id = 0;
				creditor.creditor_province =debt_province;
			}else{
				creditor.company_id =findCompany.user_id;
				creditor.creditor_province =findCompany.address;
				
			}
			creditor.status = t_creditor_right_debt.CreditorRightDebtStatus.CONFIRM.code;
			
		}
		boolean flag = creditorRightDebtDao.save(creditor);
		if(!flag){
			result.code = -1;
			result.msg = "登记账款信息失败！";
			return result;
		}
		// 数据保存成功，即进行消息通知
		Map<String, Object> parame = new HashMap<String, Object>();
		
		Map<String, String> userEventParam = new HashMap<String, String>();
		userEventParam.put("userName", company_info.full_name);
		userEventParam.put("ip",Request.current().remoteAddress.toString());
		
		if (type == 1 && findCompany != null && findCompany.user_id > 0) {
			parame.put("user_name", debt_person_name);// 需要确认债务的债务企业
			parame.put("company", company_info.full_name);// 登记债权的债务企业
			parame.put("contract_num",
					contract_num);// 登记债权的合同编号
			parame.put("creditor_money",
					creditor_money);// 登记债权的债务企业
			noticeService.sendSysNotice(findCompany.user_id,
					NoticeScene.CREDITOR_INFOR_REGIST_OK, parame);
			
			
			userService.addUserEvent(company_info.user_id, t_event_user.Event.REGISTER_RECEIVABLE_INFO, userEventParam);
			
		}
		if (type == 0){
			parame.put("user_name", company_info.full_name);// 需要确认债务的债务企业
			parame.put("contract_num", contract_num);// 需要确认债务的债务企业
			noticeService.sendSysNotice(company_info.user_id,
					NoticeScene.DEBT_TO_AFFIRM, parame);
			
			
			userService.addUserEvent(company_info.user_id, t_event_user.Event.REGISTER_PAYABLE_INFO, userEventParam);
			
		}
		result.code = 1;
		result.msg = "登记账款信息成功！";
		return result;
	}

	/**
	 * 微信端-账户中心-交易管理-合同债权
	 * 
	 * @param showType
	 *            0 债务 1 债权
	 * @param company_id
	 *            企业用户id
	 * @param currPage
	 * @param pageSize
	 * @param status
	 *            债权状态
	 * @param checkin_time
	 *            开始时间
	 * @param to_checkin_time
	 *            结束时间
	 * @return PageBean<t_creditor_right_debt>
	 * @author liangqiongfeng
	 * @version 2018-5-3 下午7:20:42
	 */
	public PageBean<t_creditor_right_debt> pagetoCreditorRight(int showType,
			long company_id, int currPage, int pageSize, int status,
			String checkin_time, String to_checkin_time) {

		return creditorRightDebtDao.pagetoCreditorRight(showType, company_id,
				currPage, pageSize, status, checkin_time, to_checkin_time);
	}
	
	
	/**
	 * 微信端-账户中心-交易管理-合同债权-金额计算
	 * 
	 * @param showType
	 *            0 债权 1 债务
	 * @param company_id
	 *            企业用户user_id
	 * @param type 0 总金额  1，剩余金额
	 * @param crd
	 * @return
	 * @author liangqiongfeng
	 * @createDate 2018年5月3日
	 */
	public double findMoneyOfWX(int showType, long company_id, int currPage,
			int pageSize, int status, String checkin_time,
			String to_checkin_time, int type) {
		return creditorRightDebtDao.findMoneyOfWX(showType, company_id, currPage,
				pageSize, status, checkin_time, to_checkin_time,type);
		
	}

}
